/**
 * 
 */
package cn.ehuoyuan.shop.action.pay;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.github.wxpay.sdk.WXPay;
import com.github.wxpay.sdk.WXPayUtil;

import cn.ehuoyuan.common.CommomUtils;
import cn.ehuoyuan.common.Tools;
import cn.ehuoyuan.common.WXPayConfigImpl;
import cn.ehuoyuan.shop.action.frontShow.OrderPay;
import cn.ehuoyuan.shop.service.pay.PayService;

/**
 * 微信支付action
 * @author liandyao
 * @date 2017年12月10日
 * @version 1.0
 */
@Controller
@RequestMapping("/wxpayAction")
public class WxPayAction {
	Logger logger = Logger.getLogger(WxPayAction.class);
	
	@Resource
	PayService payService ;
	
	public static WXPay wxpay = null;
	public static WXPayConfigImpl config = null ;
	static {
		
		try {
			config = WXPayConfigImpl.getInstance();
		 
			wxpay = new WXPay(config);
		} catch (Exception e) { 
			e.printStackTrace();
		}
	}
	/**
	 * 页面调用此方法,返回一个二维码给前端,前端扫描完成即可完成支付
	 * @throws IOException 
	 */
	@RequestMapping("pay")
	public void weixin_pay(String orderId,HttpServletRequest request,HttpServletResponse response) throws IOException {
		response.setCharacterEncoding("UTF-8");
		Writer os = response.getWriter();
		OrderPay op = null;
		if(Tools.isEmpty(orderId)) {
			logger.info("未获取到订单............");
			return ;
		}else {
			logger.info("校验订单是否已经被支付............"); 
			op = payService.getOrderPay(orderId);
			if(op==null) { //订单不存在或者订单已支付
				logger.info("订单不存在或者订单已经支付了......");  
				
				os.write("no_not found Order"); 
				 
				return ;
			} 
		}
		HashMap<String, String> data = new HashMap<String, String>();
        data.put("body", CommomUtils.PAY_ORDER_NAME+"-微信支付");
        data.put("out_trade_no", orderId);
        data.put("device_info", "");
        data.put("fee_type", "CNY");
        data.put("total_fee", Tools.moneyYuanToFen(op.getPayMoney())); //支付金额
        data.put("spbill_create_ip", request.getRemoteAddr());
        data.put("notify_url", config.getNotifyPath());
        data.put("trade_type", "NATIVE");
        data.put("product_id", "ehuoyuan");
        // data.put("time_expire", "20170112104120"); 
        logger.info("============"+data);
        try {
            Map<String, String> map = wxpay.unifiedOrder(data);
            String result_code = map.get("result_code");
            if("FAIL".equals(result_code)) {
            	logger.info("支付失败"+orderId);
            	os.write("no_"+"OK");
            }
            logger.info("============"+map);
            String urlCode = (String) map.get("code_url");  
            logger.info("二维码生成:"+urlCode);
            if(!Tools.isEmpty(urlCode)) {
            	os.write("yes_"+qrCode(urlCode));
            	return ;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
        	os.close();
        }
	}

	@RequestMapping("notify")
	public void weixin_notify(HttpServletRequest request,HttpServletResponse response) throws Exception{  
		logger.info("微信支付回调进来了.........");
		//读取参数  
		InputStream inputStream ;  
		StringBuffer sb = new StringBuffer();  
		inputStream = request.getInputStream();  
		String s ;  
		BufferedReader in = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));  
		while ((s = in.readLine()) != null){  
			sb.append(s);  
		}  
		in.close();  
		inputStream.close();  

		//解析xml成map  
		Map<String, String> m = new HashMap<String, String>();  
		m = WXPayUtil.xmlToMap(sb.toString());  

		//过滤空 设置 TreeMap  
		Map<String,String> packageParams = new TreeMap<String,String>();        
		Iterator it = m.keySet().iterator();  
		while (it.hasNext()) {  
			String parameter = (String) it.next();  
			String parameterValue = m.get(parameter);  

			String v = "";  
			if(null != parameterValue) {  
				v = parameterValue.trim();  
			}  
			packageParams.put(parameter, v);  
		}  

		// 账号信息  
		String key = WXPayConfigImpl.getInstance().getKey(); // key  

		logger.info(packageParams);  
		//判断签名是否正确  
		if(WXPayUtil.isSignatureValid(packageParams,key)) {  
			//------------------------------  
			//处理业务开始  
			//------------------------------  
			String resXml = "";  
			if("SUCCESS".equals((String)packageParams.get("result_code"))){  
				// 这里是支付成功  
				//////////执行自己的业务逻辑////////////////  
				String mch_id = (String)packageParams.get("mch_id");  
				String openid = (String)packageParams.get("openid");  
				String is_subscribe = (String)packageParams.get("is_subscribe");  
				String out_trade_no = (String)packageParams.get("out_trade_no");  

				String total_fee = (String)packageParams.get("total_fee");  
				String transaction_id = (String)packageParams.get("transaction_id");//微信支付订单号

				logger.info("mch_id:"+mch_id);  
				logger.info("openid:"+openid);  
				logger.info("is_subscribe:"+is_subscribe);  
				logger.info("out_trade_no:"+out_trade_no);  
				logger.info("total_fee:"+total_fee);  

				//////////执行自己的业务逻辑////////////////  
				int rows = payService.saveOrder(out_trade_no, transaction_id, total_fee,CommomUtils.PAY_TYPE_WXPAY);
				if(rows<=0){
					resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"  
							+ "<return_msg><![CDATA[本地订单状态变更失败]]></return_msg>" + "</xml> "; 
				}else {
					logger.info("支付成功");  
					//通知微信.异步确认成功.必写.不然会一直通知后台.八次之后就认为交易失败了.  
					resXml = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>"  
							+ "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> ";  
				}
  
			} else {  
				logger.info("支付失败,错误信息：" + packageParams.get("err_code"));  
				resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"  
						+ "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";  
			}  
			//------------------------------  
			//处理业务完毕  
			//------------------------------  
			BufferedOutputStream out = new BufferedOutputStream(  
					response.getOutputStream());  
			out.write(resXml.getBytes());  
			out.flush();  
			out.close();  
		} else{  
			logger.info("通知签名验证失败");  
		}  

	}  
	
	/**
	 * 使用腾讯的接口生成二维码.返回链接地址
	 * @param content
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	public static String qrCode(String content) throws UnsupportedEncodingException {
		//{nonce_str=jW2u0XaVFxp7JhZ3, code_url=weixin://wxpay/bizpayurl?pr=xquCh7f, appid=wx291dcc1ea85e0755, sign=F4C947CDAE5DD8EA99CF2378846AFE25D25893E68ED40B06FA545CE0736874B7, trade_type=NATIVE, return_msg=OK, result_code=SUCCESS, mch_id=1491576502, return_code=SUCCESS, prepay_id=wx20171210182815e537a0bf700683280333}
		//String chl = "weixin://wxpay/bizpayurl?pr=xquCh7f";
		int widhtHeight = 300;  
		content = URLEncoder.encode(content, "UTF-8").replace("+", "%20");  // 特殊字符处理  
		//http://mobile.qq.com/qrcode?url=TEXT&width=300&height=300
		String qrCode = "http://mobile.qq.com/qrcode?url="+content+"&width="+widhtHeight+"&height="+widhtHeight;  

		return qrCode;

	}
	 
	
	public static void main(String[] args) {
		String content = "weixin://wxpay/bizpayurl?pr=xquCh7f";
		try {
			 qrCode(content) ;
		} catch (UnsupportedEncodingException e) { 
			e.printStackTrace();
		}
		
	}
}
